package _07_串;

public class _482_密钥格式化 {


    public static void main(String[] args) {
        _482_密钥格式化 v = new _482_密钥格式化();
        String str = "--aa-aa-aa-aa--";
        int k = 2;
        System.out.println(v.licenseKeyFormatting(str, k));
    }

    public String licenseKeyFormatting(String s, int k) {
        char[] chars = s.toCharArray();
        int len = chars.length;
        int newLen = len + len / k - (len % k == 0? 1: 0);
        char[] newAry = new char[newLen];
        int newPoint = newLen - 1;
        int count = 0;
        // 逆序存放入新数组中
        for (int i = len - 1; i >= 0; i--) {
            int cur = chars[i];
            if (cur != '-') {
                if (count == k) {
                    newAry[newPoint--] = '-';
                    count = 0;
                }
                newAry[newPoint--] = (char) ((cur & 64) == 0? cur: (cur & 0x5f));
                count++;
            }
        }
        return new String(newAry, newPoint + 1, newLen - newPoint - 1);
    }

    // 利用StringBuilder
    public String licenseKeyFormatting1(String s, int k) {
        StringBuilder sb = new StringBuilder();
        int count = 0;
        // 逆序遍历字符串
        char[] chars = s.toCharArray();
        for (int i = chars.length - 1; i >= 0; i--) {
            char cur = chars[i];
            if (cur != '-') {
                if (count == k) {
                    sb.append("-");
                    count = 0;
                }
                sb.append((char)(cur & 64) == 0? cur: (cur & 0x5f));
                count++;
            }
        }
        return sb.reverse().toString();
    }

}
